import React from 'react';
import { connect } from 'dva';
import {
  ActivityIndicator,
  Menu,
  RefreshControl,
  ListView,
  Icon,
  List,
  WingBlank,
  WhiteSpace,
  SearchBar,
} from 'antd-mobile';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import Container from '../components/Base/Container';
import styles from './PrecisionPage1.css';
import MyIcon from '../components/Base/MyIcon';
import VipListShow from '../components/Base/VipListShow';
import _ from 'lodash';
import { fetchItemCls } from '../services/taskService';

const Item = List.Item;
const Brief = Item.Brief;


class P extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      page: 0,
      refreshing: false,
      isLoading: false,
      hasMore: true,
      show: false,
      value: '',
      selectValue: [2, 0],
      filter: {},
      searchKey: '',
    };
  }

  toggleScroll = () => {
    if (this.state.show) {
      document.querySelector('html').style.overflow = 'hidden';
      document.querySelector('body').style.overflow = 'hidden';
    } else {
      document.querySelector('html').style.overflow = '';
      document.querySelector('body').style.overflow = '';
    }
  }

  onChange = (value) => {
    let label = '';
    this.props.initData.forEach((dataItem) => {
      if (dataItem.value === value[0]) {
        // label = dataItem.label;
        if (dataItem.children && value[1]) {
          dataItem.children.forEach((cItem) => {
            if (cItem.value === value[1]) {
              label += ` ${cItem.label}`;
            }
          });
        }
      }
    });
    this.setState({
      show: !this.state.show,
      selectValue: value,
      label,
    }, () => {
      this.setState({ filter: this.getFilter() });
      this.props.fetch(this.getFilter());
      this.toggleScroll();
    });
  };

  onSearch = (value) => {
    let filter = {};
    if (value) {
      filter = {
        $or: [
          { vip_name: value },
          { tel: value },
          { card_no: value },
          { card_id: value },
          { mobile: value },
        ],
      };
    }
    this.setState({ filter });
    this.props.fetch(filter);
  };
  onCancel = () => {
    this.setState({ filter: {}, searchKey: '' });
    this.props.fetch({});
  };
  getFilter = () => {
    const { selectValue } = this.state;
    const type = selectValue[0];
    const value = selectValue[1];
    let filter = {};
    if (type === 2) {
      if (value) {
        filter = { ...filter, ...{ vip_level: value } };
      }
    }
    if (type === 3) {
      if (value) {
        const start = moment().subtract(value[1], 'months').toISOString();
        const end = moment().subtract(value[0], 'months').toISOString();
        filter = { ...filter, ...{ birthday: { $gt: start, $lte: end } } };
      }
    }
    if (type === 4) {
      if (value === '') {
        filter = { ...filter };
      } else if (value === 0) {
        filter = { ...filter, ...{ consume_count: null } };
      } else if (_.isString(value) && value.indexOf('>') === 0) {
        filter = { ...filter, ...{ consume_count: { $gte: parseInt(value.replace('>', '')) } } };
      } else if (_.isArray(value)) {
        filter = { ...filter, ...{ consume_count: { $gte: value[0], $lte: value[1] } } };
      } else {
        filter = { ...filter, ...{ consume_count: value } };
      }
    }
    if (type === 5) {
      if (value) {
        if (value.indexOf('>') === 0) {
          filter = { ...filter, ...{ vip_consume_money: { $gt: parseInt(value.replace('>', '')) } } };
        } else if (value.indexOf('<=') === 0) {
          filter = { ...filter, ...{ vip_consume_money: { $lte: parseInt(value.replace('<=', '')) } } };
        } else if (_.isArray(value)) {
          filter = { ...filter, ...{ vip_consume_money: { $gt: value[0], $lte: value[1] } } };
        } else {
          filter = { ...filter, ...{ vip_consume_money: value } };
        }
      }
    }

    if (type === 6) {
      filter = { ...filter, ...{ item_cls: value } };
    }
    if (type === 7) {
      filter = { ...filter, ...{ item_brand: value } };
    }
    if (type === 8) {
      filter = { ...filter, ...{ vip_item_cls: value } };
    }
    if (type === 9) {
      filter = { ...filter, ...{ vip_item_brand: value } };
    }
    if (type === 10) {
      filter = { ...filter, ...{ card_type: value } };
    }

    return filter;
  };

  getMonths = (birthday) => {
    if (birthday) {
      const months = moment().diff(moment(birthday), 'months');
      const years = Math.floor(months / 12);
      return years > 0 ? `${years}岁${months % 12}个月` : `${months % 12}个月`;
    }
    return null;
  };

  getVipType = (type) => {
    switch (type) {
      case 'A':
        return '核心会员';
      case 'B':
        return '忠诚会员';
      case 'C':
        return '普通会员';
      case 'D':
        return '低效会员';
      case 'E':
        return '流失会员';
      case 'F':
        return '新注册会员';
      default:

    }
  };
  hasMore = () => {
    const { page, totalPageCount } = this.props.vips.meta;
    return page < totalPageCount;
  };
  clear = () => {
    this.setState({ value: '' });
  };
  handleClick = (e) => {
    e.preventDefault();
    this.setState({
      show: !this.state.show,
    }, () => {
      this.toggleScroll();
    });
  };
  renderRow = (rowData, sectionID, rowID) => {
    return (
      <VipListShow
        rowData={rowData} click={() => {
          this.props.toVipInfoPage(rowData, this.props.location.query);
        }}
      />
    );
  };


  getTile = () => {
    return this.props.location.query.title;
  };

  componentDidMount() {
    // if (this.props.location.action === 'PUSH') {
      this.props.fetch();
    // }
    const top = localStorage.getItem('task_vip_list_scroll');
    if (top) {
      window.scrollTo(0, parseInt(top, 10));
    }
    setTimeout(() => {
      this.props.fetchItemCls();
      this.props.fetchBrandsTop10();
      this.props.fetchVipTypes();
    }, 2000);

    this.props.stv(true);
  }

  componentWillUnmount() {
    localStorage.setItem('task_vip_list_scroll', document.body.scrollTop || document.documentElement.scrollTop);
    document.querySelector('html').style.overflow = '';
    document.querySelector('body').style.overflow = '';
  }

  render() {
    const { data, meta } = this.props.vips;
    const { show } = this.state;
    const { initData } = this.props;
    const menuEl = (

      <Menu
        className={styles.vip_menu}
        data={initData}
        value={this.state.selectValue}
        onChange={this.onChange}
      />
    );
    const loadingEl = (
      <div
        style={{
          width: '100%',
          display: 'flex',
          justifyContent: 'center',
        }}
      >
        <ActivityIndicator size="large" />
      </div>
    );
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });

    return (
      <Container title={this.getTile()} navOption={{ rightContent: <div onClick={this.handleClick}>筛选</div> }}>
        <div className={show ? styles.menu_active : ''}>
          {show ? initData ? menuEl : loadingEl : null}

          <div className={styles.search}>
            <WingBlank size="sm">
              <SearchBar
                placeholder="输入手机号或卡号或姓名"
                onSubmit={this.onSearch}
                onCancel={this.onCancel}
                value={this.state.searchKey}
                onChange={(text) => {
                  this.setState({
                    searchKey: text,
                  });
                }}
              />
            </WingBlank>
          </div>
          <WingBlank size="sm">

            <WhiteSpace size="sm" />

            <ListView
              dataSource={dataSource.cloneWithRows(data)}
              renderRow={this.renderRow}
              renderSeparator={null}
              renderFooter={() => <div
                style={{ padding: 30, textAlign: 'center' }} onClick={() => {
                  this.props.fetchNextPage(this.state.filter);
                }}
              >
                {!this.hasMore() ? '已全部加载完' : this.props.isLoading ? '加载中...' : '下一页'}
              </div>}
              renderHeader={() => <div size="small">

                <MyIcon
                  type="trips" color="#ff2828" size="xxs"
                  style={{ position: 'relative', top: 2, marginRight: 8 }}
                />

                总计： <span style={{ color: 'red' }}>{meta.totalCount} 人</span> {this.state.label}</div>}
              initialListSize={this.props.vips.data.length}
              pageSize={20}
              scrollRenderAheadDistance={200}
              scrollEventThrottle={20}
              useBodyScroll
              style={{ marginBottom: -60 }}
            />
          </WingBlank>
        </div>
      </Container>
    );
  }
}

const caculateInitData = (itemCls, brandsTop10, vipTypes) => {
  const initData = [
    {
      value: 1,
      label: '全部',
      isLeaf: true,
    },
    {
      value: 2,
      label: '会员类型',
      children: [
        {
          label: '全部',
          value: 0,
          disabled: false,
        },
        {
          label: '核心会员',
          value: 'A',
        }, {
          label: '忠诚会员',
          value: 'B',
        }, {
          label: '普通会员',
          value: 'C',
        }, {
          label: '低效会员',
          value: 'D',
        }, {
          label: '流失会员',
          value: 'E',
        }, {
          label: '新注册会员',
          value: 'F',
        }],
    },
    {
      value: 3,
      label: '宝宝年龄',
      children: [
        {
          label: '全部',
          value: 0,
        }, {
          label: '孕早期',
          value: [-9, -7],
        }, {
          label: '孕中期',
          value: [-7, -3],
        }, {
          label: '孕晚期',
          value: [-3, 0],
        }, {
          label: '一个月内',
          value: [0, 1],
        }, {
          label: '1-3个月',
          value: [1, 3],
        }, {
          label: '3-6个月',
          value: [3, 6],
        }, {
          label: '6-12个月',
          value: [6, 12],
        }, {
          label: '12-36个月',
          value: [12, 36],
        }, {
          label: '36个月以上',
          value: [36, 120],
        }],
    },
    {
      value: 4,
      label: '消费次数',
      children: [
        {
          label: '全部',
          value: '',
        }, {
          label: '无消费',
          value: 0,
        }, {
          label: '1次',
          value: 1,
        }, {
          label: '1-3次',
          value: [1, 3],
        }, {
          label: '3-5次',
          value: [3, 5],
        }, {
          label: '5-10次',
          value: [5, 10],
        }, {
          label: '10次以上',
          value: '>10',
        }],
    },
    {
      value: 5,
      label: '客单价',
      children: [
        {
          label: '全部',
          value: '',
        }, {
          label: '小于100元',
          value: '<=100',
        }, {
          label: '100-200元',
          value: [100, 200],
        }, {
          label: '200-250元',
          value: [200, 250],
        }, {
          label: '250-300元',
          value: [250, 300],
        }, {
          label: '大于300元',
          value: '>300',
        }],
    },
  ];

  let items = { value: 6, label: '品类', children: [{ label: '全部', value: '' }] };
  for (let i = 0; i < itemCls.length; i++) {
    items.children.push({ label: itemCls[i].item_clsname, value: _.trim(itemCls[i].item_clsno) });
  }
  initData.push(items);

  items = { value: 7, label: '品牌', children: [{ label: '全部', value: '' }] };
  for (let i = 0; i < brandsTop10.length; i++) {
    items.children.push({ label: brandsTop10[i].item_brandname, value: brandsTop10[i]._id });
  }
  initData.push(items);

  items = { value: 8, label: '品类新客', children: [{ label: '全部', value: '' }] };
  for (let i = 0; i < itemCls.length; i++) {
    items.children.push({ label: itemCls[i].item_clsname, value: _.trim(itemCls[i].item_clsno) });
  }
  initData.push(items);

  items = { value: 9, label: '品牌新客', children: [{ label: '全部', value: '' }] };
  for (let i = 0; i < brandsTop10.length; i++) {
    items.children.push({ label: brandsTop10[i].item_brandname, value: brandsTop10[i]._id });
  }
  initData.push(items);

  if (vipTypes && vipTypes.length) {
    const vipItems = { value: 10, label: '会员等级', children: [{ label: '全部', value: '' }] };
    for (let i = 0; i < vipTypes.length; i++) {
      vipItems.children.push({ label: vipTypes[i].type_name, value: _.trim(vipTypes[i].type_id) });
    }
    initData.push(vipItems);
  }

  return initData;
};

export default connect((state, props) => {
  const taskType = props.location.query.taskType;
  const subType = props.location.query.subType;


  return {
    vips: state.task[`vips${taskType}${_.isNil(subType) ? '' : subType}`],
    loading: state.loading.models.task,
    itemCls: state.task.itemCls,
    brandsTop10: state.task.brandsTop10,
    initData: caculateInitData(state.task.itemCls, state.task.brandsTop10, state.vip.vipTypes),
  };
},
  (dispatch, props) => {
    return {
      fetch(filter) {
        const { branch_no } = props.location.query;
        if (branch_no) {
          filter = filter || {};
          filter.branch_no = branch_no;
        }
        dispatch({
          type: 'task/fetchVips',
          payload: { ...props.location.query, filter },
        });
      },
      fetchNextPage(filter) {
        const { taskType, subType } = props.location.query;
        dispatch({
          type: 'task/fetchNextPageVip',
          payload: { taskType, subType, filter },
        });
      },
      toVipInfoPage(rowData, query) {
        dispatch(routerRedux.push({
          pathname: '/p1_info',
          query: { cardId: rowData.card_id, cardNo: rowData.card_no, ...query, check: "1" },
        }));
      },
      fetchItemCls() {
        dispatch({ type: 'task/fetchItemCls', payload: {}, quiet: true });
      },
      fetchBrandsTop10() {
        dispatch({ type: 'task/fetchBrandsTop10', payload: {}, quiet: true });
      },
      fetchVipTypes() {
        dispatch({ type: 'vip/fetchVipTypes', payload: {}, quiet: true });
      },
      stv(flag) {
        dispatch({ type: 'task/stv', payload: flag});
      }
    };
  },
)(P);
